package com.sky.task;


import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class OrderTask {
    private static final Logger log = LoggerFactory.getLogger(OrderTask.class);
    @Autowired
    private OrdersMapper ordersMapper;
    private static final Integer MAX_UNPAID_ORDER_DURATION = 15;
    /**
     * 每分钟从第0秒开始, 也就是每分钟进行未支付订单的查询并及时修改状态
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processUnpaidOrders() {
        log.info("开始对超时且未支付订单进行扫描");
        // 10:00下单, 10:16扫描就应该修改状态, -15分钟, 10:01>10:00
        LocalDateTime time = LocalDateTime.now().minusMinutes(MAX_UNPAID_ORDER_DURATION);
        // 查询订单, 条件: 未支付且time>order_time
        List<Orders> ordersList = ordersMapper.selectUnpaid(Orders.PENDING_PAYMENT, time);
        if(ordersList != null && !ordersList.isEmpty()) {
            // 存在超时且未支付的订单
            ordersList.forEach(order -> {
                order.setStatus(Orders.CANCELLED);  //设置已取消
                order.setCancelReason(MessageConstant.OUT_OF_TIME_UNPAID);
                order.setCancelTime(LocalDateTime.now());
                // 更新订单
                ordersMapper.update(order);
            });
        }

    }

    /**
     * 把一直处于派送中的订单改成以完成
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0 16 21 * * ?") // TODO: 测试使用
    public void processOnRunning() {
        log.info("把一直处于派送中的订单改成以完成");
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = ordersMapper.selectUnpaid(Orders.DELIVERY_IN_PROGRESS, time);
        if(ordersList != null && !ordersList.isEmpty()) {
            // 一直派送中订单
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);  //设置已完成
                order.setDeliveryTime(LocalDateTime.now()); // 设置送达时间
                // 更新订单
                ordersMapper.update(order);
            });
        }

    }
}
